import storeUtils from "utils/StoreUtils";

const menuHandler = {
	loadMenus() {
		let menusArray = storeUtils.getStore("menus");
		return menusArray ? menusArray : [
			{
				"id": 1,
				"name": "system",
				"title": "系统",
				"icon": "el-icon-s-platform",
				"level": 1,
				"permission": 1,
				"hasChildren": true,
				"path": null,
				"titleEn": "System",
				"group": "common",
				"children": [
					{
						"id": "1-1",
						"name": "menus",
						"title": "菜单",
						"icon": "el-icon-menu",
						"hasChildren": false,
						"path": "/system/menus",
						"children": null,
						"permission": 6,
						"level": 2,
						"pid": 1,
						"titleEn": "Menus",
						"group": "development"
					}
				]
			}
		];
	},
	//更新菜单列表信息
	updateMenus(data, menuArray) {
		let level = Number(data.level);
		if (level === 1) {//更新父级菜单
			this.updateData(data, menuArray);
		} else if (level === 2) {//更新子级菜单
			for (let menu of menuArray) {
				this.updateData(data, menu.children);
			}
		} else if (level === 3) {//更新孙级菜单
			for (let menu of menuArray) {
				if (this.hasChildren(menu)) {
					for (let child of menu.children) {
						this.updateData(data, child.children);
					}
				}
			}
		}
		return menuArray;
	},

	updateData(data, array) {
		if (array && array.length > 0) {
			for (let item of array) {
				if (item.id.toString() === data.id.toString()) {
					data.titleEn = data.titleEn.toString().trim();
					data.children = data.hasChildren ? data.children : null;
					item = Object.assign({}, data);
					return;
				}
			}
		}
	},

	allMenuNames() {
		return this.getMenuNames({}, this.loadMenus());
	},

	getMenuNames(menuNames, menus) {
		menus.forEach(menu => {
			if (!menuNames[menu.name]) {
				menuNames[menu.name] = menu.id.toString();
			}
			if (this.hasChildren(menu)) {
				this.getMenuNames(menuNames, menu.children);
			}
		});
		return menuNames;
	},

	createMenuCn() {
		return this.loadMenuI18n(this.loadMenus(), {}, false);
	},

	createMenuEn() {
		return this.loadMenuI18n(this.loadMenus(), {}, true);
	},

	loadMenuI18n(array, menuI18n, isEn) {
		if (array && array.length > 0) {
			array.forEach(menu => {
				if (!menuI18n[menu.name]) {
					menuI18n[menu.name] = isEn ? menu.titleEn.toString().trim() : menu.title.toString().trim();
				}
				if (this.hasChildren(menu)) {
					this.loadMenuI18n(menu.children, menuI18n, isEn);
				}
			});
		}
		return menuI18n;
	},

	hasChildren(menu) {
		return menu.hasChildren && menu.children && menu.children.length > 0;
	}
};

export default menuHandler;
